﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;

namespace Sekolah
{
    public class AppConfig
    {
        public const string VIDEO_DEVICE_KEY = "VideoDevice";
        public const string CARD_READER_KEY = "CardReader";
        public const string DATABASE_KEY = "DatabaseConnection";


        private static string _appConfigPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Sekolah\\configuration.txt";
        private static ExeConfigurationFileMap _configMap = new ExeConfigurationFileMap {ExeConfigFilename = _appConfigPath};
        private static Configuration _config = ConfigurationManager.OpenMappedExeConfiguration(_configMap, ConfigurationUserLevel.None);

        public static string ReadSetting(string key)
        {
            var _appSettings = _config.AppSettings.Settings;
            if (_appSettings.AllKeys.ToList().Contains(key) && !string.IsNullOrEmpty(_appSettings[key].Value))
            {
                return _appSettings[key].Value;
            }
            throw new ConfigurationErrorsException("Error reading app settings");
        }

        public static void AddUpdateAppSettings(string key, string value)
        {
            try
            {
                //var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = _config.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }
                _config.Save();
                ConfigurationManager.RefreshSection(_config.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException)
            {
                throw new ConfigurationErrorsException("Error writing app settings");
            }
        }
    }
}
